package io.hellsinger.vortex.ui.component

import android.content.Context
import android.content.res.ColorStateList
import android.view.Gravity.CENTER
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView

class LoadingView(
    context: Context,
) : LinearLayout(context) {
    private val progressView =
        ProgressBar(context).apply {
            isIndeterminate = true
        }
    private val titleView =
        TextView(context).apply {
            textSize = 18F
            textAlignment = TEXT_ALIGNMENT_CENTER
            layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT)
            updatePadding(
                0,
                16.dp,
                0,
                0,
            )
        }

    var title: CharSequence?
        get() = titleView.text
        set(value) {
            ensureContainingTitle()
            titleView.text = value
        }

    private val containsProgressView
        get() = progressView in children

    private val containsTitleView
        get() = titleView in children

    init {
        orientation = VERTICAL
        gravity = CENTER

        addView(progressView)
    }

    fun setTitleColor(color: Int) {
        titleView.setTextColor(color)
    }

    fun setProgressColor(color: Int) {
        progressView.progressTintList = ColorStateList.valueOf(color)
    }

    private fun ensureContainingTitle() {
        if (!containsTitleView) {
            addView(titleView)
        }
    }
}
